'use strict';

// todoPage controller
app.controller('goodsInformation', ['$state','$filter','$window','$http','$scope','$modal','toaster','$log', function($state,$filter,$window,$http,$scope,$modal,toaster,$log) {
    $scope.title = {
        title:'货品资料列表',
        addTitle:'货品资料信息'
    };
    $scope.toaster = {
        type: 'warning',
        title: '提示：',
        text: '内容不能为空！'
    };
    $scope.pop = function(){
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    };
    function showMessage(type,title,text){
        $scope.toaster.type = type;
        $scope.toaster.text = text;
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    }
    function checkItems(){
        var items = ['goodsinformationHpmc',
            'goodsinformationNumber',
            'goodsinformationHpxh',
            'goodsinformationHpdj','goodsinformationHpdw','goodsinformationHplb'];
        var itemsValue = ['货品名称','货品编码','货品型号','货品单价','货品单位','货品类别'];
        for(var i=0;i<items.length;i++){
            if($('#'+items[i]+'').val()===''){
                $('#'+items[i]+'').focus();
                showMessage('warning','',itemsValue[i]+"不能为空！");
                return false;
            }
        }
        return true;
    }

    function addDo(){
        var notesdata = {};
        if(!$scope.row.goodsinformationId){
            notesdata = {
                "goodsinformationId":"",
                "qy":$("#qy").prop("checked"),
                "zdr":$scope.app.userName,
                "zdrId":$scope.app.userId,
                "goodsinformationNumber":$("#goodsinformationNumber").val(),
                "goodsinformationHpmc":$("#goodsinformationHpmc").val(),
                "goodsinformationHpxh":$("#goodsinformationHpxh").val(),
                "goodsinformationHplb":$("#goodsinformationHplb").val(),
                "goodsinformationHplbid":$("#goodsinformationHplbid").val(),
                "goodsinformationHpdw":$("#goodsinformationHpdw").val(),
                "goodsinformationBzgs":$("#goodsinformationBzgs").val(),
                "goodsinformationHpdj":$("#goodsinformationHpdj").val(),
                "goodsinformationHpdj1":$("#goodsinformationHpdj1").val(),
                "goodsinformationHpdj2":$("#goodsinformationHpdj2").val(),
                "goodsinformationHpdj3":$("#goodsinformationHpdj3").val(),
                "goodsinformationBz":$("#goodsinformationBz").val()
            }
        }else{
            notesdata = {
                "goodsinformationId":$scope.row.goodsinformationId,
                "qy":$("#qy").prop("checked"),
                "goodsinformationNumber":$("#goodsinformationNumber").val(),
                "goodsinformationHpmc":$("#goodsinformationHpmc").val(),
                "goodsinformationHpxh":$("#goodsinformationHpxh").val(),
                "goodsinformationHplb":$("#goodsinformationHplb").val(),
                "goodsinformationHplbid":$("#goodsinformationHplbid").val(),
                "goodsinformationHpdw":$("#goodsinformationHpdw").val(),
                "goodsinformationBzgs":$("#goodsinformationBzgs").val(),
                "goodsinformationHpdj":$("#goodsinformationHpdj").val(),
                "goodsinformationHpdj1":$("#goodsinformationHpdj1").val(),
                "goodsinformationHpdj2":$("#goodsinformationHpdj2").val(),
                "goodsinformationHpdj3":$("#goodsinformationHpdj3").val(),
                "goodsinformationBz":$("#goodsinformationBz").val()
            }
        }
        var info="";
        toaster.postInfo('/a_yongan/add/goodsinformation',notesdata).then(function(data){
            if(data && data.data && data.data.success){
                showMessage('seccess','','保存成功！');
                $scope.warehouseAdd = !($scope.warehouseAdd);
                $scope.warehouseList = !($scope.warehouseList);
                getGoodsTypeList();
                getList();
                return info;
            }else{
                showMessage('warning','',"保存失败！");
                info = "请求错误！";
            }
        });
        return info;
    }
    function getList(){
        toaster.getInfo('/a_yongan/list/goodsinformation',null).then(function(data){
            if(data && data.data && data.data.data){
                makeData(data.data.data);
                setTimeout(function(){
                    $('.table').trigger('footable_redraw');
                }, 100);
            }
        });
    }
    $scope.showSelectGoodsType = function(name,id){
        var modalInstance = $modal.open({
            templateUrl: 'selectGoods.html',
            controller: 'selectGoodsTypeCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $("#"+name).val(selectedItem.name);
            $("#"+id).val(selectedItem.id);
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    getList();
    function makeData(data){
        data.forEach(function (item) {
            item.createTime = $filter("date")(item.createTime, "yyyy/MM/dd");
            if(item.qy=='true'){
                item.qy = true;
                item.status = '使用中...';
                item.status1 = 'label bg-info';
            }else{
                item.qy = false;
                item.status = '禁用中...';
                item.status1 = 'label bg-danger';
            }
        })
        $scope.saveDate = data;
        $scope.saveDateAll = data;
    }
    $scope.message = '是否确定保存？';
    $scope.goodsinformationSave = function (size) {
        if(!checkItems()){
            return;
        }
        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: size,
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            var info = addDo();
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.isshow=true;
    $scope.warehouseAdd = false;
    $scope.warehouseList = true;
    $scope.goodsinformationJump = function(path) {
        $scope.row = {};
        $scope.showFiles = [];
        $scope.row = {
            'createTime':$filter("date")(new Date(), "yyyy/MM/dd"),
            'zdr':$scope.app.userName,
            'qy':true,
            'goodsinformationNumber':'HP'+$filter("date")(new Date(), "yyyyMMddHHmmss")
        };
        $scope.showKuCun = false;
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
        getGoodsTypeList();
    };
    $scope.row = {};
    $scope.columns = [
        {
            title:'货品编号',
            show:true
        },
        {
            title:'货品名称',
            show:true
        },
        {
            title:'货品型号',
            show:true
        },
        {
            title:'货品类别',
            show:true
        },
        {
            title:'库存数量',
            show:true
        },
        {
            title:'创建时间',
            show:true
        },
        {
            title:'状态',
            show:true
        }
    ];
    $scope.showSelectDept = function(id){
        var modalInstance = $modal.open({
            templateUrl: 'selectDept.html',
            controller: 'selectDeptCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $('#'+id+'').val(selectedItem.name);
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.saveDate=[];
    $scope.showInfo = function(row){
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
        $scope.row = row;
        $scope.showKuCun = true;
        getAllFile();
    };

    $scope.showFiles = [];
    $scope.upFile=function(){
        var obj = $("#uploadFile")[0];
        var isHaveFile = false;
        $scope.showFiles.forEach(function(item){
            if(item.myFileRealName===obj.files[0].name){
                isHaveFile = true;
            }
        });
        if(isHaveFile){
            showMessage('warning','',"已存在同名文件或重复文件！");
            return false;
        }
        $scope.showFiles.push({
            myFileRealName:obj.files[0].name,
            myFileSize:obj.files[0].size,
            isSuccess:false,
            isCancel:false,
            isError:false,
            isUploading:false,
            progress:0,
            file:obj.files[0]
        });
    };
    $scope.doupFile=function(index){
        uploadFiles(index);
    };

    function makeFileData(data){
        data.forEach(function(item){
            item.progress = 100;
            item.isSuccess = true;
            item.isCancel = true;
            item.isError = false;
            item.isUploading = true;
        });
        $scope.showFiles = data;
    }
    function getAllFile(){
        toaster.getInfo('/a_yongan/file/getallfile/'+$scope.row.goodsinformationNumber,null).then(function(data){
            if(data && data.data && data.data.success){
                makeFileData(data.data.data);
            }
        });
    }
    $scope.deleteFile = function (index) {
        if(!$scope.showFiles[index].isUploading){
            $scope.showFiles.splice(index,1);
        }else{
            toaster.getInfo('/a_yongan/file/deletefile/'+$scope.showFiles[index].myFileId,null).then(function(data){
                if(data && data.data && data.data.success){
                    $scope.showFiles.splice(index,1);
                    showMessage('success','','删除成功！');
                }else{
                    showMessage('warning','','删除失败！');
                }
            });
        }
    };
    function uploadFiles(index){
        $scope.showFiles[index].isUploading = true;
        var formData = new FormData();
        //formData.append("file",$("#uploadFile")[0].files[0]);//append()里面的第一个参数file对应permission/upload里面的参数file
        formData.append("file",$scope.showFiles[index].file);
        $.ajax({
            type:"post",
            async:true,  //这里要设置异步上传，才能成功调用myXhr.upload.addEventListener('progress',function(e){}),progress的回掉函数
            Accept:'text/html;charset=UTF-8',
            data:formData,
            //contentType:'multipart/form-data',
            url: '/a_yongan/file/upload/goodsinformation/'+$scope.row.goodsinformationNumber,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            xhr:function(){
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // check if upload property exists
                    myXhr.upload.addEventListener('progress',function(e){
                        var loaded = e.loaded;                  //已经上传大小情况
                        var total = e.total;                      //附件总大小
                        var percent = Math.floor(100*loaded/total);     //+"%"已经上传的百分比
                        $scope.showFiles[index].progress = percent;
                        //$("#processBar").css("width",percent);
                    }, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            success:function(data){
                if(data.success){
                    showMessage('success','','上传成功！');
                    $scope.showFiles[index].myFileId = data.error;
                    $scope.showFiles[index].progress = 100;
                    $scope.showFiles[index].isUploading = true;
                    $scope.showFiles[index].isSuccess = true;
                }else{
                    showMessage('warning','',data.error);
                    $scope.showFiles[index].isUploading = false;
                    $scope.showFiles[index].isSuccess = false;
                }
            },
            error:function(){
                showMessage('warning','','上传失败！');
                $scope.showFiles[index].isUploading = false;
                $scope.showFiles[index].isError = true;
            }
        });
    }


    $scope.setting = {
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeClick: showDetail
        }
    };
    var selectNodeId = {};
    function showDetail(treeId, treeNode, clickFlag){
        //此处进行列表筛选，显示子节点列表
        $scope.saveDate = [];
        $scope.saveDateAll.forEach(function(item){
            if(treeNode.id==1){
                $scope.saveDate.push(item);
            }else{
                if(treeNode.name==item.goodsinformationHplb){
                    $scope.saveDate.push(item);
                }
            }
        });
        selectNodeId = treeNode;
        $scope.$apply();
        setTimeout(function(){
            $('.table').trigger('footable_redraw');
        }, 100);
    }
    function getGoodsTypeList(){
        $scope.doing_async = true;
        toaster.getInfo('/a_yongan/selectlist/goodtype',null).then(function(data){
            if(data && data.data && data.data.data){
                madeTree(data.data.data);
            }
        });
    }
    function madeTree(data){
        setTimeout(function() {
            $.fn.zTree.init($("#mytree"), $scope.setting, data);
        },100);
        $scope.doing_async = false;
    }
    getGoodsTypeList();

    $scope.showChangeInfo = function(goods){
        var goodsData = {
            "goods":goods,
            "data":[]
        };
        toaster.getInfo('/a_yongan/list/goodschangeinfo/'+goods.goodsinformationNumber,null).then(function(data){
            if(data && data.data && data.data.success){
                console.log("data.data：",data.data.data);
                goodsData.data = data.data.data;
                var modalInstance = $modal.open({
                    templateUrl: 'showGoodsChangeInfo.html',
                    controller: 'showGoodsChangeInfoCtrl',
                    size: 'lg',
                    resolve: {
                        items: function () {
                            return goodsData;
                        }
                    }
                });
                modalInstance.result.then(function (selectedItem) {

                }, function () {
                    $log.info('Modal dismissed at: ' + new Date());
                });
            }else{
                showMessage('warning','','获取详情失败！');
            }
        });

    };
}])
;